import React, { useEffect, useState } from 'react'
import { Menu, Spin } from 'antd'
import { getMenuList } from '@/api/modules/login'
import { useLocation, useNavigate } from 'react-router-dom'
import { useSelector, useDispatch } from '@/store'
import { setMenuList as reduxSetMenuList } from '@/store/modules/menu'
import { setAuthRouter } from '@/store/modules/auth'
import { handleRouter, getOpenKeys } from '@/utils'
import * as Icons from '@ant-design/icons'

export default function LayoutMenu() {
  const dispatch = useDispatch()
  const { isCollapse, menuList: reduxMenuList } = useSelector(
    (state) => state.menu
  )

  const navigator = useNavigate()
  const [menuList, setMenuList] = useState([])
  const [loading, setLoading] = useState(false)
  const { pathname } = useLocation()
  const [selectedKeys, setSelectedKeys] = useState([pathname])
  const [openKeys, setOpenKeys] = useState([])

  const getItem = (label, key, icon, children) => {
    return {
      key,
      icon,
      children,
      label,
    }
  }
  const addIcon = (icon) => {
    return React.createElement(Icons[icon])
  }
  const deepLoopFloat = (menuList = [], newArr = []) => {
    menuList.forEach((item) => {
      if (item.children && item.children.length > 0) {
        newArr.push(
          getItem(
            item.title,
            item.path,
            addIcon(item.icon),
            deepLoopFloat(item.children)
          )
        )
      } else {
        newArr.push(getItem(item.title, item.path, addIcon(item.icon)))
      }
    })
    return newArr
  }

  const getMenuData = async () => {
    setLoading(true)
    try {
      const { data } = await getMenuList()
      setMenuList(deepLoopFloat(data))
      // 设置menuList
      dispatch(reduxSetMenuList(data))
      // 把路由菜单处理成一维数组，存储到redux中，做权限判断
      const dynamicRouter = handleRouter(data)
      dispatch(setAuthRouter(dynamicRouter))
    } finally {
      setLoading(false)
    }
  }
  const clickMenu = ({ key }) => {
    navigator(key)
  }
  const onOpenChange = (openKeys = []) => {
    if (openKeys.length === 0 || openKeys.length === 1)
      return setOpenKeys(openKeys)
    const latestOpenKey = openKeys[openKeys.length - 1]
    if (latestOpenKey.includes(openKeys[0])) return setOpenKeys(openKeys)
    setOpenKeys([latestOpenKey])
  }
  useEffect(() => {
    getMenuData()
  }, [])

  // 刷新页面菜单保持高亮
  useEffect(() => {
    setSelectedKeys([pathname])
    if (!isCollapse) {
      setOpenKeys(getOpenKeys(pathname))
    }
  }, [pathname, isCollapse])

  return (
    <Spin spinning={loading} tip="Loading...">
      <Menu
        theme="dark"
        mode="inline"
        triggerSubMenuAction="click"
        items={menuList}
        selectedKeys={selectedKeys}
        openKeys={openKeys}
        onClick={clickMenu}
        onOpenChange={onOpenChange}
      />
    </Spin>
  )
}
